<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryData.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addUserDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 根据data数据 帮我们自动生成表格 -->
      <el-table :data="users" stripe border>
        <!-- label：列标题prop：告诉这一列选那一个数据 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="switchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserShow(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="clickDel(scope.row)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 8, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      @close="dialogClose"
      title="添加用户"
      :visible.sync="addUserDialog"
      width="50%"
    >
      <!-- model 用来记录整个表单的数据 -->
      <el-form
        ref="addUserFormRef"
        :rules="addUserRules"
        :model="addUserForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      @close="editUserClose"
      title="修改用户"
      :visible.sync="editUseDialogVisible"
      width="50%"
    >
      <el-form
        ref="editUserForm"
        :rules="addUserRules"
        :model="userInfo"
        label-width="80px"
      >
        <el-form-item label="用户名:">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="userInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUseDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      @close="selectValue = ''"
      width="50%">
      <div>
        <div>当前的用户：{{userInfo.username}}</div>
        <div>当前的角色：{{userInfo.role_name}}</div>
        <div>
          选择新角色：
          <!-- v-model: 双向数据绑定 -->
          <el-select v-model="selectValue" placeholder="请选择">
            <!-- value: 将选中的值记录到 v-model 的数据 -->
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSetRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱校验规则
    const checkEmail = (rule, value, cb) => {
      // rule 当前的校验规则
      // value 当前的校验规则要校验的值 邮箱输入框的值
      // cb 不管成功或失败要调用的回调
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (!reg.test(value)) {
        return cb(new Error('邮箱格式不正确'))
      }
      cb()
    }
    // 自定义手机号校验规则
    const checkMobile = (rule, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return cb(new Error('手机号格式不正确'))
      }
      cb()
    }
    return {
      // 获取用户列表数据
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 1
      },
      // 用户列表数据
      users: [],
      // 总条数
      total: 0,
      addUserDialog: false,
      // 记录整个表单数据
      addUserForm: {
        username: '卢本伟',
        password: '123123',
        email: '123@qq.com',
        mobile: '13000000000'
      },
      // 表单规则正则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑按钮显示与隐藏
      editUseDialogVisible: false,
      // 记录点击每一行的用户信息
      userInfo: {},
      // 分配角色按钮显示与隐藏
      setRolesDialogVisible: false,
      // 接收角色列表
      roles: [],
      selectValue: ''
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        // params 给后台传递的参数
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.users = res.data.users
      this.total = res.data.total
    },
    // 选择了每页多少条触发
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 点击翻页（页码发生变化）触发
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 开关变化
    async switchChange (userInfo) {
      const { id, mg_state: state } = userInfo
      const { data: res } = await this.$axios.put(`users/${id}/state/${state}`)
      if (res.meta.status !== 200) return this.$message.error('修改用户状态失败')
      this.$message.success('修改用户成功')
    },
    // 关闭对话框
    dialogClose () {
      // resetFields 对整个表单进行重置
      this.$refs.addUserFormRef.resetFields()
    },
    // 点击确定,实现添加用户功能
    clickAddUser () {
      // validate 校验表单是否校验通过
      this.$refs.addUserFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('创建用户失败')
        this.$message.success('创建用户成功')
        // 关闭对话框
        this.addUserDialog = false
        // 重新加载页面
        this.getUserList()
      })
    },
    // 点击编辑按钮显示编辑对话框
    editUserShow (row) {
      this.editUseDialogVisible = true
      // 在data中定义userInfo
      console.log(row)
      this.userInfo = JSON.parse(JSON.stringify(row))
    },
    // 监听编辑用户对话框关闭
    editUserClose () {
      this.$refs.editUserForm.resetFields()
    },
    // 点击确定按钮进行用户编辑
    editUser () {
      this.$refs.editUserForm.validate(async flag => {
        if (!flag) return
        const { id, email, mobile } = this.userInfo
        const { data: res } = await this.$axios.put('users/' + id, { email, mobile })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.editUseDialogVisible = false
        this.getUserList()
      })
    },
    // 点击了删除按钮
    clickDel (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('users/' + row.id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功!')
        this.getUserList()
      }).catch(() => {
        // 直接调用$message === $message.info()
        this.$message.info('已取消删除')
      })
    },
    // 点击了分配角色按钮
    async showSetRoles (row) {
      this.userInfo = row
      this.setRolesDialogVisible = true
      // 获取角色列表
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.roles = res.data
    },
    // 点击保存更新用户角色
    async saveSetRoles () {
      // 判断是否选择角色
      if (!this.selectValue) return this.$message.error('请选择角色')
      // 发送请求
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.selectValue })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.setRolesDialogVisible = false
      this.getUserList()
    }
  }
}
</script>

<style scoped lang='less'>
</style>
